package com.assets.util;

import com.assets.newNHF.util.LogUtils;
import com.google.gson.Gson;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MyOkHttp {
    private OkHttpClient okHttpClient;
    private Gson gson = new Gson();
    private volatile static MyOkHttp myOkhttp = null;

    private MyOkHttp() {
        okHttpClient = new OkHttpClient
                .Builder()
                .hostnameVerifier(new AllowAllHostnameVerifier())
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request originalRequest = chain.request();
                        Request compressedRequest = originalRequest.newBuilder()
                                .header("Accept-E4ncoding", "gzip")
                                .build();
                        return chain.proceed(compressedRequest);
                    }
                })
                .sslSocketFactory(TrustAllCerts.createSSLSocketFactory(), TrustAllCerts.getX509TrustManager())
                .connectTimeout(10, TimeUnit.SECONDS)//连接超时
                .readTimeout(500, TimeUnit.SECONDS)
                .build();//读超时  还有一个写超时
    }

    public static MyOkHttp getInstance() {
        if (myOkhttp == null) {
            return newInstance();
        }
        return myOkhttp;
    }

    private synchronized static MyOkHttp newInstance() {
        if (myOkhttp == null) {
            myOkhttp = new MyOkHttp();
        }
        return myOkhttp;
    }


    public void get(String url, final requestMessage requestMessage) {
        final Request request = new Request.Builder().addHeader("Content-Type", "application/json; charset=utf-8").get().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                requestMessage.requestFail();
                requestMessage.requestComplete();
            }

            @Override
            public void onResponse(final Call call, Response response) throws IOException {
                requestMessage.requestComplete();
                if (response.isSuccessful()) {
                    requestMessage.requestSuccess(response);
                } else {
                    requestMessage.requestFail();
                    LogUtils.e(response.message());
                }
            }
        });
    }

    public void post(String url, Map<String, String> param, final requestMessage requestMessage) {
        FormBody.Builder builder = new FormBody.Builder();
        if (param != null) {
            for (Map.Entry<String, String> entry : param.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        Request request = new Request.Builder()
                .post(builder.build())
                .url(url)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtils.d(e.toString());
                e.printStackTrace();
                requestMessage.requestFail();
                requestMessage.requestComplete();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                requestMessage.requestComplete();
                if (response.isSuccessful()) {
                    requestMessage.requestSuccess(response);
                } else {
                    requestMessage.requestFail();
                    LogUtils.d(response.body().string());
                }
            }
        });
    }

    public void postBitMap(String url, File file, String assetNumber, final requestMessage requestMessage) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        builder.addFormDataPart("picture", "img.jpg", RequestBody.create(MediaType.parse("image/jpg"), file));
        builder.addFormDataPart("assetNumber", assetNumber);
        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                requestMessage.requestFail();
                requestMessage.requestComplete();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                requestMessage.requestComplete();
                if (response.isSuccessful()) {
                    requestMessage.requestSuccess(response);
                } else {
                    requestMessage.requestFail();
                    LogUtils.d(response.message());
                }
            }
        });
    }

    //系统时间获取方法
    public String getDate() {
        //获取系统的日期时间
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
        return sdf.format(calendar.getTime());
    }

    //系统时间获取方法
    public String getTime() {
        //获取系统的日期时间
        Calendar calendar = Calendar.getInstance();
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat, Locale.ENGLISH);
        return sdf.format(calendar.getTime());
    }

    public Gson getGson() {
        return gson;
    }


    public interface requestMessage {
        void requestFail();

        //失败成功都会回调
        void requestComplete();

        void requestSuccess(Response response) throws IOException;
    }
}
